/**
 * 权限菜单管理JS
 * 
 */
var parentId = 1;
var departmentName = '权限菜单';//父节点名称
//var permissionLeaf = false;//是否为节点
var departmentDataTable;//数据表
var setting;//Ztree设置

//table显示ID
var tableDiv="departmentDataTable";
//表单DIV
var formDiv = "addSysDepartmentVOForm";
//添加对话框
var addDlgDiv ="addSysDepartmentVODiv";
//添加按钮
var addBtn = "SysDepartmentVOAddBtn";
//新增按钮  
var addDlgVO = "addSysDepartmentVO";

//对象查询地址
var queryUrl="../system/sysDepartmentVO/querySysDepartmentVOPageList";
//对象增加地址
var addUrl="../system/sysDepartmentVO/saveSysDepartmentVO"
//对象修改地址
var updateUrl="../system/sysDepartmentVO/updateSysDepartmentVOById"
//对象删除地址
var deleteUrl="../system/sysDepartmentVO/deleteSysDepartmentVOById"
//对象详情地址
var detailUrl="../system/sysDepartmentVO/querySysDepartmentVOById"

$(function () {
	    setting = {
			data:{
				simpleData:{
					enable : true,
					idKey : "departmentId",
					pIdKey : "departmentParent",
					rootPId:null
				},
				key:{
					name:"departmentName",
					leaf:'1'
				}
			},
			callback:{onClick: zTreeOnClick}
	    };
	    reloadTree();//数据表据重新加载
		//数节点点击回调函数
		function zTreeOnClick(event, treeId, treeNode){
			//获取当前dict允许创建的组织机构层数
			findDepartmentFloorByDict(treeNode.level);
			parentId = treeNode.departmentId;
			departmentName = treeNode.departmentName;
//			permissionLeaf = (treeNode.permissionLeaf!=0);
			departmentDataTable.ajax.reload();
		};
	
     //权限数据表
     departmentDataTable = $('#departmentDataTable').DataTable({
    	 	"bProcessing": true,
            "bLengthChange":true,
            "bFilter": false,//无搜索 
            "bServerSide": true,//服务端数据处理
            "bSort": false,//排序功能
            "pagingType":"full_numbers",
            "sAjaxSource": "../system/sysDepartmentVO/querySysDepartmentVOPageList",//后端服务地址
            "fnServerParams" : function(aDataSet) {aDataSet.push({"name" : "departmentParent","value" : parentId});},
            "fbServerData":function(sSource,aDataSet){$.ajax({"dataType":"json","type":"GET","url":sSource,"data":aDataSet});},
            "aoColumns":[{"mDataProp":"departmentName"},{"mDataProp":"departmentCode"},{"mDataProp":"departmentDesc"},{"mDataProp":"departmentId"}],
            "aoColumnDefs":[
         	               {"aTargets":[3],"mRender":function(data,type,full) {
         	            	   return "<button class='btn btn-lightblue btn-outline m-wrap' style='font-size:12px;line-height:15px;' data-id='"+data+"' data-json='"+JSON.stringify(full)+"' data-name='"+full.departmentName+"' id='updateDataBtn'><i class='icon-pencil'></i></button>" +
         	            	  "&nbsp;&nbsp;"+"<button class='btn btn-lightpink btn-outline m-wrap' style='font-size:12px;line-height:15px;' data-id='"+data+"' data-name='"+full.departmentName+"' id='dltBtn'><i class='icon-remove'></i></button>";}
            }],
            "oLanguage":{"sUrl": "../resources/assets/plugins/dataTables/txt/page.txt"},
            "initComplete":function () {
	             $('#departmentDataTable_length').find('select').selectpicker('render');
	             $('#departmentDataTable_length').find('select').selectpicker('refresh');
	             $('#departmentDataTable_length').find('.btn-group').css('width','auto');
	             $('#departmentDataTable_length').find('.btn').css('background-color','#fff');
	             $('#departmentDataTable_length').find('.btn').css('border','#d8d8d8 solid 1px')
	            }
            });
     
    //删除功能菜单操作
 	$('#departmentDataTable tbody').on('click','#dltBtn',function(){
		var name = $(this).attr("data-name");
		var id = $(this).attr("data-id");
		confirm("您确定删除["+name+"]？", function(isConfirm){
			if (isConfirm) {$.post(deleteUrl+"?departmentId="+id,function(data){if(data){reloadTree();departmentDataTable.ajax.reload();swal("成功", "当前操作成功 :)", "success");}else{swal("失败", data.errorMsg, "error");}});} 
			else {swal("取消", "您的操作已经取消 :)", "error");}
		});
 	});
 	
 	var tabForm = $('#' + formDiv);
    var errorForm = $('.alert-error', tabForm);
    var successForm = $('.alert-success', tabForm);
	//初始化表单-新增和删除
	function initFormValidate(param){
		var url="";
		if(param=="add"){
			url=addUrl;
			$("#"+formDiv+" #departmentParent").val(parentId);
		}else if(param=="update"){
			url=updateUrl;
		}
		$("#"+formDiv + " #departmentParent").val(parentId)
		$("#"+formDiv).attr("action",url);
		
		//表单验证(新)
		$("#"+formDiv).validate({
	        errorElement: 'span', //default input error message container
	        errorClass: 'help-inline', // default input error message class
	        focusInvalid: false, // do not focus the last invalid input
	        ignore: "",
	        rules: {
	        		departmentName:{required:true,}, 
	        		departmentCode:{
	        			required:true,
	        			remote:{
	        				type:'post',
	        				url:'../system/sysDepartmentVO/codeVaild',
	        				async:false,
	        				data: {
	        					departmentCode:function(){
	        						return $("#addSysDepartmentVOForm #departmentCode").val();
	        					},
	        					departmentId:function(){
	        						return $("#addSysDepartmentVOForm #departmentId").val();
	        					},
	        					addType:param
	        				},
	        				dataType: "json",
	        				dataFilter:function (data){
	        					return data;
	        				}
	        			}
	        		}, 
	        		departmentParent:{required:true,}
	        },
	        invalidHandler: function (event, validator) { //display error alert on form submit              
	            successForm.hide();
	            errorForm.show();
	            App.scrollTo(errorForm, -200);
	        },
	        highlight: function (element) { // hightlight error inputs
	            $(element).closest('.help-inline').removeClass('ok'); // display OK icon
	            $(element).closest('.control-group').removeClass('success').addClass('error'); // set error class to the control group
	        },
	        unhighlight: function (element) { // revert the change dony by hightlight
	            $(element).closest('.control-group').removeClass('error'); // set error class to the control group
	        },
	        success: function (label) {
	            label.addClass('valid').addClass('help-inline ok') // mark the current input as valid and display OK icon
	            label.closest('.control-group').removeClass('error').addClass('success'); // set success class to the control group
	        },
	        messages:{departmentName:{pattern:'必须是汉字'},departmentCode:{remote:'部门编号不可重复!'}},
	        submitHandler: function (form) {
	            successForm.show();
	            errorForm.hide();
	            valditFlag = true;//防止重复录入
	            /**
	    		 * 自定义属性
	    		 * 拼接成json对象
	    		 */
	    		var extJson = {};
//	    		extJson.bbb = "bbb";
//	    		extJson.aaa = "aaa";
	    		var extJsonStr = "departmentExtJson="+JSON.stringify(extJson);
	    		var postData = $("#"+formDiv).serialize();
	    		
	    		var dataTT = postData+"&"+extJsonStr;
	            $.post(tabForm.attr("action"),dataTT,function(data){
					if(data.flg==true){
						swal("成功","操作成功", "success");
						$("#"+addDlgDiv).modal("hide");
						reloadTree();
						reloadData();
					}else if(data.flg==false){
						swal("失败","操作失败","error");
						$("#"+addDlgDiv).modal("hide");
						reloadTree();
						reloadData();
					}
				});
	            return false;
	        }
   		});
   		
	}
	
	
	//新增按钮
	$("#"+addDlgVO).bind("click",function(){
		reset();
		$("#"+addBtn).text("保存");
		$("#" + formDiv+ " #"+addBtn).attr("disabled",false);
		valditFlag =false;
		$("#"+ addDlgDiv).modal("show");
		initFormValidate("add");
	});
	
	//新增数据保存按钮
	$("#"+addBtn).on("click",function(){
		if(valditFlag){
			return;
		}
		$('#' + formDiv).submit();
		resetRequired();
	});
	
	//修改
	$("#"+tableDiv+" tbody").on("click","#updateDataBtn",function(){
		var pk=$(this).attr("data-id");
		$("."+formDiv+"_checktip").html(""); 
		reset();
		$("#"+addBtn).text("修改");
		$.ajax({url:detailUrl,data:{departmentId:pk},type:"post",async:false,success:function(data){
			if(data !=null && typeof(data)!="undefined"){
				for(var k in data){
					var ele =$("#"+formDiv+" #"+k);
					ele.val(data[k]);
				}
				$('#zzjgcj').selectpicker('val',data.departmentHierarchy);
				valditFlag = false;
				$("#"+ addDlgDiv).modal("show");
				initFormValidate("update");
			}
		}
		});
		initFormValidate("update");
	});
	
	//初始化表单
	function reset(){
		$("#"+formDiv).find("input").val("");
		$("#"+formDiv).find("select").val("");
		$('#zzjgcj').selectpicker('val','');
		$(".help-inline").closest('.control-group').removeClass('ok');
   		$(".help-inline").closest('.control-group').removeClass('error');
   		$(".help-inline").closest('.control-group').removeClass('success');
   		$(".help-inline").removeClass('ok');
   	    $(".help-inline").html('');
   	    $("br[name='br']").remove();
   	    $(".alert-success").attr("display","none");
   	    $(".alert-error").attr("display","none");
   	    $(".alert-error").attr("style","");
   	    $(".alert-success").attr("style","");
	}
	
	//修改验证样式
	function resetRequired(){
	}
 	
 		
});
//获取当前dict允许创建的组织机构层数
function findDepartmentFloorByDict(nowFloor){
	 $.post("../system/sysDepartmentVO/findDepartmentFloorByDict",function(data){
		 if((nowFloor+1)==data){
			 $("#addSysDepartmentVO").addClass("hide");
		 }else{
			 $("#addSysDepartmentVO").removeClass("hide");
		 }

	 });
}

//数据Tree重新加载
function reloadTree(){
	 $.post("../system/sysDepartmentVO/querySysDepartmentVOPageList?iDisplayStart=0&iDisplayLength=10000000",function(data){
		 var newData = data.aaData;
		 $.fn.zTree.init($("#departmentZTree"), setting, newData).expandAll(true);});
}	
function reloadData(){
	departmentDataTable.ajax.reload();
}
